package com.yqg.manage.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yqg.manage.entity.Menu;
import com.yqg.manage.mapper.UnitMenuMapper;
import com.yqg.manage.service.IRoleMenuService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yqg.manage.common.Result;

import com.yqg.manage.service.IUnitMenuService;
import com.yqg.manage.entity.UnitMenu;

import org.springframework.web.bind.annotation.RestController;

/**
 * UnitMenuController 前端控制器
 *
 * @author zxf
 * @since 2025-09-16
 */
@RestController
@RequestMapping("/unit-menu")
public class UnitMenuController {

    @Resource
    private IUnitMenuService unitMenuService;
    @Resource
    private UnitMenuMapper unitMenuMapper;

    @Resource
    private IRoleMenuService roleMenuService;

    /**
     * 新增或者更新
     */
    @PostMapping("/edit")
    public Result save(@RequestBody UnitMenu unitMenu) {
        return Result.success(unitMenuService.saveOrUpdate(unitMenu));
    }

    /**
     * 删除
     */
    @GetMapping("delete/{id}")
    public Result delete(@PathVariable Integer id) {
        UnitMenu unitMenu = unitMenuService.getById(id);
        return Result.success(unitMenuService.saveOrUpdate(unitMenu));
    }

    /**
     * 查询所有
     */
    @GetMapping("/all")
    public Result findAll() {
        QueryWrapper<UnitMenu> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_delete", "0");
        List<UnitMenu> list = unitMenuService.list(queryWrapper);
        return Result.success(list);
    }

    /**
     * 根据id查询
     */
    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(unitMenuService.getById(id));
    }

    /**
     * 分页查询
     */
    @GetMapping("/page")
    public Result findPage(@RequestParam Integer pageNum,
                           @RequestParam Integer pageSize) {
        QueryWrapper<UnitMenu> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_delete", "0");
        queryWrapper.orderByDesc("id");
        return Result.success(unitMenuService.page(new Page<>(pageNum, pageSize), queryWrapper));
    }

    /**
     * 查询当前单位最大菜单
     * @param unitId 单位ID
     */
    @GetMapping("/getUnitMaxMenu")
    public Result getUnitMaxMenu(@RequestParam Long unitId) {

        List<Menu> menuList = unitMenuMapper.getUnitMaxMenu(unitId);
        List<Menu> treeMenu = menuList.stream()
                .filter(i -> i.getPid() == null)
                .map(i -> {
                    i.setMenuDtos(getChildren(i, menuList));
                    return i;
                })
                .collect(Collectors.toList());
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            String json = objectMapper.writeValueAsString(treeMenu);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        return Result.success(treeMenu);
    }


    private static List<Menu> getChildren(Menu node, List<Menu> list) {
        return list.stream()
                //当 参数的节点 == 循环的父节点（说明参数的节点 找到儿子了）
                .filter(i -> node.getId().equals(i.getPid()))
                //再次递归设置调用
                .map(i -> {
                    i.setMenuDtos(getChildren(i, list));
                    return i;
                })
                .collect(Collectors.toList());
    }

    /**
     * 获取角色实际菜单的ID
     */
    @GetMapping("/getUnitMenu")
    public Result getUnitMenu(@RequestParam Long unitId) {
        List<Long> byRoleId = roleMenuService.getDataByUnitId(unitId);

        return Result.success(byRoleId);
    }


}

